using System;
using System.Collections.Generic;
using System.Text;
using Dune.Business.Domain.Forum;
using Dune.Business.Domain.Users;
using Edge.Common;
using Edge.Common.Utils;
using Edge.DAL.Common;
using Edge.DAL.Managers;
using NHibernate;
using NHibernate.Expression;

namespace Dune.DAL.Managers
{
    class PostManager : AbstractManager<Post, int, User>, IPostManager
    {
        public ICollection<Post> GetPosts(int id)
        {
            IList<Post> ret = null;
            using (IDalOperation op = CreateLoadOperation())
            {
                ICriteria criteria = CreateCriteria();
                if (id != 0)
                    criteria.Add(Expression.Eq("Theme.Id", id));
                else
                    criteria.Add(Expression.IsNull("Theme"));
                ret = criteria.List<Post>();
                op.Commit();
            }
            return ret;
        }

        public ICollection<Post> Find(FetchOptions fetchOptions, PostFilter filter)
        {
            try
            {
                ICriteria criteria = CreateCriteria(fetchOptions);
                AddRestrictions(criteria, filter);
                return criteria.List<Post>();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public int Count(PostFilter filter)
        {
            ICriteria criteria = CreateCriteria();
            AddRestrictions(criteria, filter);
            criteria.SetProjection(Projections.RowCount());
            return (int)criteria.List()[0];
        }

        private void AddRestrictions(ICriteria criteria, PostFilter filter)
        {
            if (!StringUtils.IsBlankOrNull(filter.GetText()))
            {
                criteria.Add(Expression.Disjunction()
                                 .Add(Expression.Like("Text", "%" + filter.GetText().Trim() + "%"))
                                 .Add(Expression.Like("CreatedBy", "%" + filter.GetText().Trim() + "%")));
            }

            if (filter.Person != null)
            {
                criteria.Add(Expression.Eq("CreatedBy", filter.Person));
            }

            if (filter.Theme != null)
            {
                criteria.Add(Expression.Eq("Theme", filter.Theme));
            }
        }
    }
}
